<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="synchronized是Java多线程处理中用于线程同步的关键字，使用它可以用非常简单的代码处理多线程同步问题，因此被广泛的使用。下面我们一起来学习下它的使用。

synchronized是Java中的关键字，是一种同步锁。用法如下：

修饰方法 - 包括普通方法（对象方法）和静态方法（类方法）
修饰代码块 - 此时需要指定需要同步的资源">
<meta property="og:type" content="article">
<meta property="og:title" content="Java中synchronized用法">
<meta property="og:url" content="https://vector-ding.coding.me/java/synchorized/index.html">
<meta property="og:site_name" content="Vector's Notes">
<meta property="og:description" content="synchronized是Java多线程处理中用于线程同步的关键字，使用它可以用非常简单的代码处理多线程同步问题，因此被广泛的使用。下面我们一起来学习下它的使用。

synchronized是Java中的关键字，是一种同步锁。用法如下：

修饰方法 - 包括普通方法（对象方法）和静态方法（类方法）
修饰代码块 - 此时需要指定需要同步的资源">
<meta property="og:updated_time" content="2017-03-11T14:59:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java中synchronized用法">
<meta name="twitter:description" content="synchronized是Java多线程处理中用于线程同步的关键字，使用它可以用非常简单的代码处理多线程同步问题，因此被广泛的使用。下面我们一起来学习下它的使用。

synchronized是Java中的关键字，是一种同步锁。用法如下：

修饰方法 - 包括普通方法（对象方法）和静态方法（类方法）
修饰代码块 - 此时需要指定需要同步的资源">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '6378305291301160000',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://vector-ding.coding.me/java/synchorized/"/>





  <title> Java中synchronized用法 | Vector's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Vector's Notes</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle"></p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-algorithm">
          <a href="/categories/algorithm/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-superscript"></i> <br />
            
            Algorithm
          </a>
        </li>
      
        
        <li class="menu-item menu-item-java">
          <a href="/categories/java/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />
            
            Java
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://vector-ding.coding.me/java/synchorized/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="vector.ding">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/assets/img/vector.ding.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Vector's Notes">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="Vector's Notes" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java中synchronized用法
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-03-10T16:05:31+08:00">
                2017-03-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/java/synchorized/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="java/synchorized/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p><code>synchronized</code>是Java多线程处理中用于线程同步的关键字，使用它可以用非常简单的代码处理多线程同步问题，因此被广泛的使用。下面我们一起来学习下它的使用。</p>
</blockquote>
<p><code>synchronized</code>是Java中的关键字，是一种同步锁。用法如下：</p>
<ol>
<li>修饰方法 - 包括普通方法（对象方法）和静态方法（类方法）</li>
<li>修饰代码块 - 此时需要指定需要同步的资源</li>
</ol>
<a id="more"></a>
<h2 id="准备测试模型类"><a href="#准备测试模型类" class="headerlink" title="准备测试模型类"></a>准备测试模型类</h2><p>测试模型类中包含多种被<code>synchronized</code>修饰的方法或者代码块，后面各个场景中会用到。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> io.vector.study.threads.sync;</div><div class="line"></div><div class="line"><span class="keyword">import</span> io.vector.study.threads.util.Threads;</div><div class="line"><span class="keyword">import</span> lombok.Getter;</div><div class="line"><span class="keyword">import</span> lombok.Setter;</div><div class="line"><span class="keyword">import</span> org.slf4j.Logger;</div><div class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Created by vector on 2017/3/10.</div><div class="line"> */</div><div class="line"><span class="meta">@Getter</span></div><div class="line"><span class="meta">@Setter</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncTestModel</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(SyncTestModel.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> Integer id = <span class="number">0</span>;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String name = <span class="string">""</span>;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Object lock = <span class="keyword">new</span> Object();</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">staticSyncMethod</span><span class="params">()</span> </span>&#123;</div><div class="line">        logger.info(<span class="string">"static synchronized method start..."</span>);</div><div class="line">        Threads.sleepOneSecond();</div><div class="line">        logger.info(<span class="string">"static synchronized method end..."</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">setNameWithMethodSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        setNameAndSleepOneSecond(name);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithStaticFieldSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (lock) &#123;</div><div class="line">            setNameAndSleepOneSecond(name);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithClassSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (SyncTestModel.class) &#123;</div><div class="line">            setNameAndSleepOneSecond(name);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithObjectSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</div><div class="line">            setNameAndSleepOneSecond(name);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithPropertySync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>.name) &#123;</div><div class="line">            setNameAndSleepOneSecond(name);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setIdWithPropertySync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>.id) &#123;</div><div class="line">            setNameAndSleepOneSecond(name);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">displayNameWithMethodSync</span><span class="params">()</span> </span>&#123;</div><div class="line">        displayName();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">displayNameWithPropertySync</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>.name) &#123;</div><div class="line">            displayName();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">displayIdWithPropertySync</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>.id) &#123;</div><div class="line">            displayName();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameAndSleepOneSecond</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        logger.info(<span class="string">"set method start... "</span> + name);</div><div class="line">        Threads.sleepOneSecond();</div><div class="line">        setName(name);</div><div class="line">        logger.info(<span class="string">"set method end... "</span>  + name);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setIdAndSleepOneSecond</span><span class="params">(Integer id)</span> </span>&#123;</div><div class="line">        logger.info(<span class="string">"set method start..."</span>);</div><div class="line">        Threads.sleepOneSecond();</div><div class="line">        setId(id);</div><div class="line">        logger.info(<span class="string">"set method end..."</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">displayName</span><span class="params">()</span> </span>&#123;</div><div class="line">        logger.info(<span class="string">"display method start..."</span>);</div><div class="line">        logger.info(<span class="string">"display method end..."</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>注意: 因为下面我们使用JUnit做测试，而JUnit中如果使用多线程，是不会等所有线程结束再结束执行，会导致看不到输出，所以这里使用了Java中的<code>CountDownLatch</code>来等待所有线程结束后再结束测试用例方法。下面展示我们用到的自定义线程类<code>WorkThread</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> io.vector.study.threads;</div><div class="line"></div><div class="line"><span class="keyword">import</span> java.util.concurrent.CountDownLatch;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Created by vector on 2017/3/10.</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WorkerThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String name;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> CountDownLatch countDownLatch;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">WorkerThread</span><span class="params">(Runnable runnable, CountDownLatch countDownLatch)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(runnable);</div><div class="line">        <span class="keyword">this</span>.countDownLatch = countDownLatch;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">WorkerThread</span><span class="params">(String name, Runnable runnable, CountDownLatch countDownLatch)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(runnable, name);</div><div class="line">        <span class="keyword">this</span>.countDownLatch = countDownLatch;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>.run();</div><div class="line">        countDownLatch.countDown();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>测试用例统一的方法执行前后逻辑如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> io.vector.study.threads;</div><div class="line"></div><div class="line"><span class="keyword">import</span> io.vector.study.threads.sync.SyncTestModel;</div><div class="line"><span class="keyword">import</span> io.vector.study.threads.util.Threads;</div><div class="line"><span class="keyword">import</span> org.junit.After;</div><div class="line"><span class="keyword">import</span> org.junit.Before;</div><div class="line"><span class="keyword">import</span> org.junit.Test;</div><div class="line"></div><div class="line"><span class="keyword">import</span> java.util.concurrent.CountDownLatch;</div><div class="line"><span class="keyword">import</span> java.util.concurrent.TimeUnit;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncMethodTest</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> CountDownLatch countDownLatch;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> SyncTestModel syncTestModel;</div><div class="line"></div><div class="line">    <span class="meta">@Before</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUp</span><span class="params">()</span> </span>&#123;</div><div class="line">        countDownLatch = <span class="keyword">new</span> CountDownLatch(<span class="number">2</span>);</div><div class="line">        syncTestModel = <span class="keyword">new</span> SyncTestModel();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@After</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">end</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// 最多等待5秒</span></div><div class="line">        countDownLatch.await(<span class="number">5</span>, TimeUnit.SECONDS);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSyncMethod</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        ...</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSyncStaticMethod</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        ...</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="修改方法"><a href="#修改方法" class="headerlink" title="修改方法"></a>修改方法</h2><ol>
<li><p>修饰普通方法</p>
<p> 直接在方法声明中加入<code>sychronized</code>关键字即可，示例:</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">setNameWithMethodSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    setNameAndSleepOneSecond(name);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 此时同步的资源对象是<code>调用该方法的对象</code>，在一个线程通过对象A调用到这段代码过程中，另一个线程也调用该对象的这个方法时，必须等待，下面为测试代码：</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testExecSameSyncMethod</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    <span class="keyword">new</span> WorkerThread(() -&gt; syncTestModel.setNameWithMethodSync(<span class="string">"hello1"</span>), countDownLatch).start();</div><div class="line">    Threads.sleepQuietly(<span class="number">10</span>);</div><div class="line">    <span class="keyword">new</span> WorkerThread(() -&gt; syncTestModel.setNameWithMethodSync(<span class="string">"hello2"</span>), countDownLatch).start();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 输出:</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="number">21</span>:<span class="number">55</span>:<span class="number">51.872</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method start... hello1</div><div class="line"><span class="number">21</span>:<span class="number">55</span>:<span class="number">52.875</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method end... hello1</div><div class="line"><span class="number">21</span>:<span class="number">55</span>:<span class="number">52.875</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method start... hello2</div><div class="line"><span class="number">21</span>:<span class="number">55</span>:<span class="number">53.879</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method end... hello2</div></pre></td></tr></table></figure>
<p> 设置方法我们故意延时一秒钟，可以看到第二个设置线程并没有立即执行，而是等第一个线程执行完才执行的，因此两个线程执行同一个对象的同一个同步方法Java可以保证线程同步。</p>
<p> 前两天在开源中国上看到一个问题：“两个线程同时执行一个对象的两个不同的同步方法，线程是否是同步的？”，你们觉得呢？<br>
 先略微思考一下：同步方法同步的资源对象是对象，注意是对象哦，两个不同的同步方法代表不同的同步代码块，两个不同的线程同时进入两个不同的代码块，看似是没有没有访问同一个资源。</p>
<p> 我们来验证下</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testExecDifferentSyncMethod</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    <span class="keyword">new</span> WorkerThread(() -&gt; syncTestModel.setNameWithMethodSync(<span class="string">"hello"</span>), countDownLatch).start();</div><div class="line">    Threads.sleepQuietly(<span class="number">10</span>);</div><div class="line">    <span class="keyword">new</span> WorkerThread(() -&gt; syncTestModel.displayNameWithMethodSync(), countDownLatch).start();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 输出</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="number">22</span>:<span class="number">10</span>:<span class="number">33.691</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method start... hello</div><div class="line"><span class="number">22</span>:<span class="number">10</span>:<span class="number">34.706</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - set method end... hello</div><div class="line"><span class="number">22</span>:<span class="number">10</span>:<span class="number">34.706</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - display method start...</div><div class="line"><span class="number">22</span>:<span class="number">10</span>:<span class="number">34.706</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - display method end...</div></pre></td></tr></table></figure>
<p> 不同线程分别执行不同的同步方法，可以看到并没有发生乱序，依然是同步的。再思考一下，同步的资源对象是<code>对象</code>，即使是不同的方法，但确是同一个对象，所以自然也是需要同步的。</p>
</li>
<li><p>修饰静态方法</p>
<p> 用法：只需要同步的静态方法声明时加入<code>synchronized</code>关键字</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">staticSyncMethod</span><span class="params">()</span> </span>&#123;</div><div class="line">    logger.info(<span class="string">"static synchronized method start..."</span>);</div><div class="line">    Threads.sleepOneSecond();</div><div class="line">    logger.info(<span class="string">"static synchronized method end..."</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 同步静态方法锁住的资源是类本身，也可以理解为锁住的是类的所有实例对象。</p>
<p> 测试代码</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSyncStaticMethod</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    Runnable staticMethodTask1 = () -&gt; SyncTestModel.staticSyncMethod();</div><div class="line">    Runnable staticMethodTask2 = () -&gt; SyncTestModel.staticSyncMethod();</div><div class="line"></div><div class="line">    <span class="keyword">new</span> WorkerThread(staticMethodTask1, countDownLatch).start();</div><div class="line">    Threads.sleepQuietly(<span class="number">10</span>);</div><div class="line">    <span class="keyword">new</span> WorkerThread(staticMethodTask2, countDownLatch).start();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 输出</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="number">22</span>:<span class="number">24</span>:<span class="number">06.171</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - <span class="keyword">static</span> <span class="keyword">synchronized</span> method start...</div><div class="line"><span class="number">22</span>:<span class="number">24</span>:<span class="number">07.176</span> [Thread-<span class="number">0</span>] INFO io.vector.study.threads.sync.SyncTestModel - <span class="keyword">static</span> <span class="keyword">synchronized</span> method end...</div><div class="line"><span class="number">22</span>:<span class="number">24</span>:<span class="number">07.177</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - <span class="keyword">static</span> <span class="keyword">synchronized</span> method start...</div><div class="line"><span class="number">22</span>:<span class="number">24</span>:<span class="number">08.177</span> [Thread-<span class="number">1</span>] INFO io.vector.study.threads.sync.SyncTestModel - <span class="keyword">static</span> <span class="keyword">synchronized</span> method end...</div></pre></td></tr></table></figure>
<p> 线程依次等待执行，是同步的。</p>
</li>
</ol>
<h2 id="修饰代码块"><a href="#修饰代码块" class="headerlink" title="修饰代码块"></a>修饰代码块</h2><p>修饰代码块时，需要指定锁定的资源，资源可以是对象或者类。</p>
<ol>
<li><p>同步资源为对象时</p>
<p> 用法</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithObjectSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</div><div class="line">        setNameAndSleepOneSecond(name);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 由于锁住的是对象，在效果上等加入一下代码</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">setNameWithMethodSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    setNameAndSleepOneSecond(name);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 但其使用上更加灵活，可以通过将代码块缩小至最小来达到提升性能的效果。</p>
</li>
<li><p>同步的资源为类时</p>
<p> 用法一：使用<code>ClassName.class</code>来锁住类</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithClassSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    <span class="keyword">synchronized</span> (SyncTestModel.class) &#123;</div><div class="line">        setNameAndSleepOneSecond(name);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p> 用法一：使用类的静态常量来锁住类</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Object lock = <span class="keyword">new</span> Object();</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNameWithStaticFieldSync</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">    <span class="keyword">synchronized</span> (lock) &#123;</div><div class="line">        setNameAndSleepOneSecond(name);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>在使用<code>synchronized</code>编写代码时，需要明确我们的场景是需要同步的资源是基于类的还是基于对象的。例如<code>HashTable</code>保证的是对象级别的线程互斥，因此只要在每个方法上加上<code>synchronized</code>关机字即可；而单例模式中的<code>懒汉模式</code>的两次检测需要锁住的就必须是类。</p>
<p>在判断<code>synchronized</code>同步情况时，依然首先需要明确锁住的资源对象，然后就可以清晰的判断出多线程之间的执行规则了。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/技术/后端/mybatis/Mybatis插入操作返回新增记录的ID/" rel="next" title="Mybatis插入操作返回新增记录的ID">
                <i class="fa fa-chevron-left"></i> Mybatis插入操作返回新增记录的ID
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/algorithm/permutations/" rel="prev" title="算法拾遗之【全排列算法】">
                算法拾遗之【全排列算法】 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="java/synchorized/"
           data-title="Java中synchronized用法" data-url="https://vector-ding.coding.me/java/synchorized/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/assets/img/vector.ding.jpg"
               alt="vector.ding" />
          <p class="site-author-name" itemprop="name">vector.ding</p>
          <p class="site-description motion-element" itemprop="description">Elegant Coding</p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#准备测试模型类"><span class="nav-number">1.</span> <span class="nav-text">准备测试模型类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改方法"><span class="nav-number">2.</span> <span class="nav-text">修改方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修饰代码块"><span class="nav-number">3.</span> <span class="nav-text">修饰代码块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vector.ding</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"vector-ding"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  












  
  

  

  

  

  

</body>
</html>
